﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;
using System.Web.Security;

using FSViet.Survey.Helpers;

namespace FSViet.Survey.Administration.Question
{
	public partial class Details : DetailsPageBase
	{

		#region QuestionType
		public QuestionTypes QuestionType
		{
			get
			{
				QuestionTypes result = QuestionTypes.ChoiseOne;
				try
				{
					result = (QuestionTypes)Convert.ToInt32(Request.QueryString["QuestionType"]);
				}
				catch
				{
				}
				return result;
			}
		}
		#endregion

		protected void Page_Load(object sender, EventArgs e)
		{
			CheckCampaign();

			if (!IsPostBack)
			{
				LoadAnswerGroup();

				if (Request.QueryString["Id"] != null)
				{
					Guid id = GlobalApplication.GetGuid(Request.QueryString["Id"]);
					if (id != Guid.Empty)
						LoadData(id);
				}
			}
		}

		void LoadAnswerGroup()
		{
			try
			{
				DataHelper dataH = new DataHelper();
				var data = dataH.Load("SELECT * FROM Questions WHERE CampaignId=@CampaignId AND QuestionType=@QuestionType ORDER BY Created", 0, 100,
					dataH.CreateParam("CampaignId", SqlDbType.Char, GlobalApplication.GetGuidS(CampaignId)),
					dataH.CreateParam("QuestionType", SqlDbType.Char, (int)QuestionTypes.AnswerGroup));

				AnswerGroupList.DataSource = data;
				AnswerGroupList.DataTextField = "Name";
				AnswerGroupList.DataValueField = "Id";
				AnswerGroupList.DataBind();
				AnswerGroupList.Items.Insert(0, new ListItem("--Specific answer group--", GlobalApplication.GetGuidS(Guid.Empty)));
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString();
#endif
			}
			
		}

		void LoadData(Guid id)
		{
			TitleLabel.Text = "Update item: " + GlobalApplication.GetGuidS(id);
			try
			{
				DataHelper dataH = new DataHelper();

				var data = dataH.Load("SELECT * FROM Questions WHERE Id='" + GlobalApplication.GetGuidS(id) + "'", 0, 1);
				FillData(data.Rows[0]);

				//show group info
				if (data.Rows[0]["GroupId"] == DBNull.Value || data.Rows[0]["GroupId"].ToString() == GlobalApplication.GetGuidS(Guid.Empty))
				{ LeaveGroupButton.Visible = false; }
				else
				{
					LeaveGroupButton.Visible = true;
					data = dataH.Load("SELECT * FROM Groups WHERE Id='" + data.Rows[0]["GroupId"].ToString() + "'", 0, 1);
					if (data.Rows.Count > 0)
					{
						GroupNameLabel.Text = data.Rows[0]["Name"].ToString();
					}
				}
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString();
#endif
			}
		}

		void FillData(DataRow data)
		{
			NameInput.Text = data["Name"].ToString().Trim();
			if (DBNull.Value == data["AnswerGroupId"] || data["AnswerGroupId"].ToString() == GlobalApplication.GetGuidS(Guid.Empty))
			{ }
			else
				AnswerGroupList.SelectedValue = data["AnswerGroupId"].ToString();
			//RenderAnswerMode
			if (DBNull.Value == data["RenderAnswerMode"])
			{ }
			else
				RenderAnswerModeList.SelectedValue = data["RenderAnswerMode"].ToString();
			//QuestionType
			if (DBNull.Value == data["QuestionType"])
			{ }
			else
				QuestionTypeList.SelectedValue = data["QuestionType"].ToString();
		}

		protected void SaveButton_Click(object sender, EventArgs e)
		{
			//if (!IsValidInput()) return;
			try
			{
				Guid id = ItemId;
				DataHelper dataH = new DataHelper();
				string userId = GlobalApplication.GetGuidS((Guid)Membership.GetUser().ProviderUserKey);
				string now = GlobalApplication.NowS;
				if (id == Guid.Empty)
				{
					dataH.Execute("INSERT INTO Questions(Id, Name, QuestionType, CampaignId, SiteId, GroupId, AnswerGroupId, RenderAnswerMode, Created, CreatedId, Modified, ModifiedId) "
						+ "VALUES(@Id, @Name, @QuestionType, @CampaignId, @SiteId, @GroupId, @AnswerGroupId, @RenderAnswerMode, @Created, @CreatedId, @Modified, @ModifiedId)",
					dataH.CreateParam("Id", SqlDbType.Char, GlobalApplication.GuidS),
					dataH.CreateParam("Name", SqlDbType.NVarChar, NameInput.Text.Trim()),
					dataH.CreateParam("QuestionType", SqlDbType.Int, Convert.ToInt32(QuestionTypeList.SelectedValue)),
					dataH.CreateParam("CampaignId", SqlDbType.Char, GlobalApplication.GetGuidS(CampaignId)),
					dataH.CreateParam("SiteId", SqlDbType.Char, GlobalApplication.GetGuidS(SiteId)),
					dataH.CreateParam("GroupId", SqlDbType.Char, GlobalApplication.GetGuidS(Guid.Empty)),
					dataH.CreateParam("AnswerGroupId", SqlDbType.Char, GlobalApplication.GetGuidS(new Guid(AnswerGroupList.SelectedValue))),
					dataH.CreateParam("RenderAnswerMode", SqlDbType.Int, Convert.ToInt32(RenderAnswerModeList.SelectedValue)),
					dataH.CreateParam("Created", SqlDbType.Char, now),
					dataH.CreateParam("CreatedId", SqlDbType.Char, userId),
					dataH.CreateParam("Modified", SqlDbType.Char, now),
					dataH.CreateParam("ModifiedId", SqlDbType.Char, userId));
				}

				else
				{
					dataH.Execute("UPDATE Questions SET Name=@Name, QuestionType=@QuestionType, "
						+"AnswerGroupId=@AnswerGroupId, RenderAnswerMode=@RenderAnswerMode, Modified=@Modified, ModifiedId=@ModifiedId "
						+" WHERE Id=@Id",
						dataH.CreateParam("Id", SqlDbType.Char, GlobalApplication.GetGuidS(id)),
						dataH.CreateParam("QuestionType", SqlDbType.Int, Convert.ToInt32(QuestionTypeList.SelectedValue)),
						dataH.CreateParam("Name", SqlDbType.NVarChar, NameInput.Text.Trim()),
						dataH.CreateParam("AnswerGroupId", SqlDbType.Char, GlobalApplication.GetGuidS(new Guid(AnswerGroupList.SelectedValue))),
						dataH.CreateParam("RenderAnswerMode", SqlDbType.Int, Convert.ToInt32(RenderAnswerModeList.SelectedValue)),
						dataH.CreateParam("Modified", SqlDbType.Char, now),
						dataH.CreateParam("ModifiedId", SqlDbType.Char, userId));
				}

				//return to list
				Response.Redirect("List.aspx");
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString();
#endif
			}
		}

		bool IsValidInput()
		{
			bool result = true;

			if (NameInput.Text.Trim().Length < 1)
			{
				result = false;
				msg.Text = "Please enter name";
			}

			return result;
		}

		protected void DeleteButton_Click(object sender, EventArgs e)
		{
			try
			{
				Guid id = GlobalApplication.GetGuid(Request.QueryString["Id"]);
				var dataH = new DataHelper();
				if (id != Guid.Empty)
				{
					var conn=dataH.CreateConnection();
					conn.Open();
					var cmd = conn.CreateCommand();
					var trans = conn.BeginTransaction();
					cmd.Transaction = trans;
					try
					{
						cmd.CommandText = "DELETE FROM Answers WHERE QuestionId='" + GlobalApplication.GetGuidS(id) + "'";
						cmd.ExecuteNonQuery();

						cmd.CommandText = "DELETE FROM Questions WHERE Id='" + GlobalApplication.GetGuidS(id) + "'";
						cmd.ExecuteNonQuery();

						trans.Commit();
					}
					catch
					{
						trans.Rollback();
						throw;
					}
					finally
					{
						conn.Close();
					}
				}

				//return to list
				if (Request.QueryString["pr"] != null)
					Response.Redirect("List.aspx?Id=" + Request.QueryString["pr"] + "&p=" + (Request.QueryString["p"] ?? "0"));
				else
					Response.Redirect("List.aspx");
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString();
#endif
			}
		}

		protected void LeaveGroupButton_Click(object sender, EventArgs e)
		{

		}
	}
}